<template>
  <div class="review">
    <p>
      {{ state.title
      }}{{ state.fillinTime ? `（更新时间：${state.fillinTime}）` : "" }}
    </p>
    <a-form
      ref="formRef"
      :model="state.formState"
      layout="vertical"
      :hideRequiredMark="readOnly || $route.params.onlyread !== 'false'"
      style="width: 100%"
    >
      <FormItem
        v-for="item in state.formConfig"
        :key="item.key"
        :formItemConfig="item"
        v-model:formState="state.formState[item.key || '']"
        :onlyRead="readOnly || $route.params.onlyread !== 'false'"
      ></FormItem>
    </a-form>
    <div
      style="width: 100%"
      v-if="
        (routeNamePrefix && +$route.params.status > 400) ||
        (routeNamePrefix === 'Approval' && $route.params.onlyread === 'false')
      "
    >
      <a-divider dashed></a-divider>
      <a-form
        ref="approvalFormRef"
        :model="formState"
        name="basic"
        layout="vertical"
        style="width: 100%"
        :hideRequiredMark="
          routeNamePrefix === 'Backend' || $route.params.onlyread !== 'false'
        "
      >
        <FormItem
          v-for="item in approvalFormConfig"
          :key="item.key"
          :formItemConfig="item"
          v-model:formState="formState[item.key || '']"
          :onlyRead="
            routeNamePrefix === 'Backend' || $route.params.onlyread !== 'false'
          "
        />
      </a-form>
    </div>
    <a-button
      v-if="
        routeNamePrefix !== 'Backend' && !($route.params.onlyread !== 'false')
      "
      type="primary"
      @click="handleSubmitClick"
      >{{ routeNamePrefix === "Approval" ? "保存" : "确定" }}</a-button
    >
  </div>
</template>
<script lang="ts" setup>
import {
  approveProjectIndicator,
  fillProjectIndicator,
  getProjectIndicatorDetailById,
} from "@/api";
import FormItem from "@/components/Form/FormItem.vue";
import { defaultFormConfig } from "@/utils";
import { getCurrentInstance, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { approvalFormConfig } from "../config";
const props = defineProps<{ readOnly: boolean; routeNamePrefix: string }>();
const formRef = ref();
const approvalFormRef = ref();
const state = reactive<{
  title: string;
  fillinTime?: string;
  formConfig: FormItem[];
  formState: Record<string, any>;
}>({
  title: "",
  fillinTime: "",
  formConfig: [],
  formState: {},
});
const route = useRoute();
const router = useRouter();
const formState = ref<Record<string, any>>({});

const { $loading } =
  getCurrentInstance()?.appContext?.config.globalProperties || {};
$loading?.start();
getProjectIndicatorDetailById({
  indicatorId: route.params.indicatorId as string,
  projectId: route.params.id as string,
})
  .then((res) => {
    const { formDefinition, formData, name, fillinTime, ...rest } = res;
    state.fillinTime = fillinTime;
    state.title = name || "";
    state.formConfig = formDefinition
      ? JSON.parse(formDefinition)
      : defaultFormConfig;
    state.formState = formData ? JSON.parse(formData) : {};
    formState.value = rest;
  })
  .catch(console.error)
  .finally(() => {
    $loading?.stop();
  });
const handleSubmitClick = async () => {
  $loading?.start();
  if (props.routeNamePrefix === "Approval") {
    handleApprovalClick();
    return;
  }
  try {
    const values = await formRef.value?.validate();
    await fillProjectIndicator({
      indicatorId: parseFloat(route.params.indicatorId as string),
      projectId: parseFloat(route.params.id as string),
      formData: JSON.stringify(values),
    });
    router.push({
      name: props.routeNamePrefix + "ProjectFill",
      params: route.params,
    });
  } catch (e) {
    console.warn(e);
  } finally {
    $loading?.stop();
  }
};
const handleApprovalClick = async () => {
  try {
    const values = await approvalFormRef.value?.validate();
    approveProjectIndicator({
      indicatorId: parseFloat(route.params.indicatorId as string),
      projectId: parseFloat(route.params.id as string),
      ...values,
    })
      .then(() => {
        router.push({
          name: props.routeNamePrefix + "ProjectFill",
          params: route.params,
        });
      })
      .catch(console.error);
  } catch (e) {
    console.error(e);
  } finally {
    $loading?.stop();
  }
};
</script>
<style lang="scss" scoped>
.review {
  display: flex;
  flex-flow: column nowrap;
  align-items: flex-start;
}
.buttons {
  text-align: center;
  & > .ant-btn {
    margin-left: 12px;
    &:first-of-type {
      margin-left: 0;
    }
  }
}
</style>
